const UserModel = require("../model/user");
const jwt = require("jsonwebtoken");
const {
  secret
} = require("../config");
const catchError = require("../utils/catchError")

const pwdReg = /^[A-Za-z0-9]+$/;
const emailReg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

class User {
  async login(ctx) {
    let {
      username,
      password
    } = ctx.request.body;

    if (!username && !password) {
      return (ctx.body = {
        code: 1,
        msg: "用户名和密码不能为空",
      });
    }

    let user = await UserModel.findOne({
      username,
      password
    }, {
      username
    });
    
    if (!user) {
      return (ctx.body = {
        code: 1,
        msg: "账号或密码输入有误",
      });
    }

    // ctx.session.user = {
    //   username: "admin",
    //   email: "admin@example.com",
    //   description: "测试一下",
    // };

    // 生成密码
    let token = jwt.sign({
      username: user.username,
      _id: user._id
    }, secret);

    ctx.body = {
      code: 0,
      msg: "登录成功",
      token: token,
      data: {
        ...user
      },
    };
  }
  async register(ctx) {
    let {
      username,
      password,
      email,
      nickname = username
    } = ctx.request.body;

    if (!username || !password || !email) {
      return (ctx.body = {
        code: 1,
        msg: "请填写完整信息",
      });
    }

    let user = await UserModel.findOne({
      username
    });

    if (user) {
      return (ctx.body = {
        code: 1,
        msg: "用户名已被占有",
      });
    }

    let emailAdd = await UserModel.findOne({
      email
    });

    if (emailAdd) {
      return (ctx.body = {
        code: 1,
        msg: "邮箱已经被注册",
      });
    }

    if (username.length < 6 || username.length > 13) {
      return ctx.body = {
        code: 1,
        msg: "用户名长度在6-13位",
      };
    }

    if (!pwdReg.test(password) || password.length < 8) {
      return ctx.body = {
        code: 1,
        msg: "密码须大于8位并由数字字母组成",
      };
    }

    if (!pwdReg.test(password)) {
      return ctx.body = {
        code: 1,
        msg: "请输入正确密码格式",
      };
    }
    // console.log(test123);

    // 将数据插入数据库

    let data = await UserModel.create({
      username,
      password,
      email,
      nickname
    });

    ctx.body = {
      code: 0,
      msg: "注册成功",
    };
  }

  // async show(ctx) {
  //   ctx.body = {
  //     code: 0,
  //     msg: "注册成功",
  //   };
  // }
}

module.exports = new User();